package com.dyz.LeetCodeforSwordFingerOffer;

/**
 * @author: daiyizheng
 * @date: 2021/7/3 11:25
 * @description:
 */
public class Search53 {
    public static void main(String[] args) {
        int [] nums = new int[]{1};
        int target = 1;
        int search = new Search53().search(nums, target);
        System.out.println(search);
    }
    public int search(int[] nums, int target) {
        //他是排好序的，暴力可以使用遍历， 提高时间复杂度可以使用二分查找
        if(nums.length==0){return -1;}
        //二分
        int count = 0;
        int left = 0;
        int right = nums.length-1;
        while (left<=right){
            int mid = (left+right)>>1;
            if(nums[mid]==target){
                //左边
                count++;
                int l = mid-1;
                while ( l>=0 && nums[l]==target){
                    count++;
                    l--;
                }
                //右边
                int r = mid +1;
                while (r<=nums.length-1 && nums[r]==target){
                    count++;
                    r++;
                }
                break;
            }else if(nums[mid]>target){
                right = mid-1;
            }else {
                left = mid+1;
            }

        }
        return count;
    }
}
